package com.reebake.ideal.message.websocket.core;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import com.reebake.ideal.constants.CommonConstants;
import com.reebake.ideal.json.util.JsonUtil;
import com.reebake.ideal.message.websocket.config.WebsocketServerConfig;
import com.reebake.ideal.message.websocket.entity.WebsocketMessageDTO;

import cn.hutool.core.util.ObjUtil;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ServerEndpoint(value = "/websocket", configurator = WebsocketServerConfig.class)
public class WebsocketServer {

    private static final Map<String, Session> sessionMap = new HashMap<>();

    private String getUserId(Session session) {
        return (String) session.getUserProperties().get(CommonConstants.ATTRIBUTE_NAME_USER_ID);
    }

    @OnOpen
    public void onOpen(Session session) {
        String userId = getUserId(session);
        sessionMap.put(userId, session);
    }
    
    @OnMessage
    public void onMessage(Session session, String message) {
    }

    @OnClose
    public void onClose(Session session) {
        String userId = getUserId(session);
        sessionMap.remove(userId);
    }

    public void sendMessage(String userId, WebsocketMessageDTO message) {
        Session session = sessionMap.get(userId);
        if(ObjUtil.isNull(session)) {
            return;
        }
        try {
            session.getBasicRemote().sendText(JsonUtil.toJsonStr(message));
        }catch (Exception e) {
            log.error("发送失败.", e);
        }
    }

    public void sendMessageToAll(WebsocketMessageDTO message) {
        Collection<Session> sessions = sessionMap.values();
        for (Session session : sessions) {
            try {
                session.getBasicRemote().sendText(JsonUtil.toJsonStr(message));
            } catch (Exception e) {
                log.error("发送失败.", e);
            }
        }
    }

}
